package com.tnovoselec.android.mojevijesti.async;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.nth.android.Util;
import com.tnovoselec.android.mojevijesti.R;
import com.tnovoselec.android.mojevijesti.dto.ChannelDto;
import com.tnovoselec.android.mojevijesti.dto.NewsItemDto;
import com.tnovoselec.android.mojevijesti.dto.NewsResultHolder;
import com.tnovoselec.android.mojevijesti.parser.NewsParser;

public class GetNewsAsync extends AsyncTask<Void, Long, Map<String, List<NewsItemDto>>> {

	public interface NewsDownloadedListener {
		public void onNewsDownloaded();
	}

	private NewsDownloadedListener listener;

	public static String TAG = GetNewsAsync.class.getSimpleName();

	public static long CACHE_VALIDITY = 1 * 60 * 1000;

	private ChannelDto channel;
	private String pathToSave;
	private boolean fromCache;
	private Context context;

	protected ProgressDialog dialog = null;
	
	public GetNewsAsync(ChannelDto channel, String pathToSave, boolean fromCache, Context context) {
		this.channel = channel;
		this.pathToSave = pathToSave;
		this.fromCache = fromCache;
		this.context = context;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(context, "", context.getResources().getText(R.string.please_wait_news), true);
	}
	
	@Override
	protected Map<String, List<NewsItemDto>> doInBackground(Void... params) {
		HttpURLConnection connection = null;
		InputStream is = null;
		Iterator<String> iter = channel.getItems().keySet().iterator();
		while (iter.hasNext()) {
			String channelName = iter.next();
			String xmlUrl = "http://anonymouse.org/cgi-bin/anon-www.cgi/" + channel.getItems().get(channelName);
			List<NewsItemDto> items;
			try {

				if (Util.fileExistsHex(xmlUrl, context) && (System.currentTimeMillis() - Util.getFileHex(xmlUrl, context).lastModified()) < CACHE_VALIDITY) {
					// is = Util.readFile(xmlUrl, context);
				} else if (!fromCache) {
					// TODO ubaciti u Util framework
					URL imageUrl = new URL(xmlUrl);
					connection = (HttpURLConnection) imageUrl.openConnection();
					connection.setConnectTimeout(Util.HTTP_CONNECT_TIMEOUT);
					connection.setReadTimeout(Util.HTTP_READ_TIMEOUT);
					connection.setDoInput(true);
					connection.connect();

					is = connection.getInputStream();
					Util.fileCreate(xmlUrl, is, context);
					//Util.fileCreate(xmlUrl, is, Config.PATH_TO_SAVE);
				}
				if (Util.fileExistsHex(xmlUrl, context)) {
					is = Util.readFile(xmlUrl, context);
				} else {
					return null;
				}

				NewsParser parser = new NewsParser();
				SAXParserFactory factory = SAXParserFactory.newInstance();
				SAXParser sp = factory.newSAXParser();
				sp.parse(is, parser);
				items = new ArrayList<NewsItemDto>();
				items = parser.getNews();
				NewsResultHolder.put(channelName, items);
			} catch (Exception ex) {
				Log.e(TAG, ex.getMessage(), ex);
				return null;
			}
		}

		return NewsResultHolder.getAll();
	}
	
	@Override
	protected void onPostExecute(Map<String, List<NewsItemDto>> result) {
		super.onPostExecute(result);
		if (listener != null){
			listener.onNewsDownloaded();
		}
		dialog.dismiss();
	}

	public void setListener(NewsDownloadedListener listener) {
		this.listener = listener;
	}
	
	

}
